﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.Mvc;
using FeaturesBlog.Models;
using FeaturesBlog.Helpers;
using FeaturesBlog.Models.Interfaces;

namespace FeaturesBlog.Controllers
{
    public class PostController : Controller
    {
        //
        // GET: /Comment/
        public IDataManager DataManager { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (DataManager == null) { DataManager = new DataManager(); }

            base.Initialize(requestContext);
        }

        public ActionResult Comments(decimal id)
        {
            Post p = DataManager.PostRepository.GetPost(id);
            PostModel model = new PostModel { BlogPost = p, CommentsCount = 0, PostWithActions = false };
            ViewData["CurrentPost"] = model;
            ViewData["Comments"] = DataManager.CommentsRepository.GetCommentsByPostId(id);
            return View();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public string GetPost(decimal id)
        {
            Post p = DataManager.PostRepository.GetPost(id);
            PostModel pm = new PostModel() { BlogPost = p, PostWithActions = true };
            pm = new HtmlHelpers().EncodeHtmlForPost(pm);
            return pm.BlogPost.PostBody;
        }

        [Authorize]
        public ActionResult Delete(decimal id)
        {
            Comment c = DataManager.CommentsRepository.GetComment(id);
            DataManager.CommentsRepository.DeleteComment(id);

            RouteValueDictionary param = new RouteValueDictionary();
            param.Add("id", c.PostId);
            return RedirectToAction("Comments", param);
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Comments(Comment c)
        {
            User u = DataManager.UserRepository.GetUser(HttpContext.User.Identity.Name);
            c.UserId = u != null ? (decimal?)u.UserId : null;
            c.IP = HttpContext.Request.UserHostAddress;
            DataManager.CommentsRepository.AddComment(c);
            (new MailHelper()).SendCommentNotification(c);
            return RedirectToAction("Comments");
        }
    }
}
